<template>
  <el-input
    v-if="showInput"
    style="width: 100%"
    v-model="selectName"
    readonly
    :placeholder="placeholder"
  >
    <template #append>
      <el-button icon="Promotion" @click="handlePicker" />
    </template>
  </el-input>
  <!-- 用户导入对话框 -->

  <!-- 添加或修改用户配置对话框 -->
  <el-dialog
    :title="title"
    v-model="open"
    :close-on-click-modal="false"
    draggable
    width="80%"
    append-to-body
  >
    <div class="dialog-container">
      <el-row :gutter="20" style="max-height: 70vh">
        <!--组织数据-->
        <el-col :span="8" :xs="24" style="max-height: 70vh; overflow: auto">
          <div class="head-container">
            <el-input
              v-model="deptName"
              placeholder="请输入组织名称"
              clearable
              prefix-icon="Search"
              style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container">
            <el-tree
              :data="deptOptions"
              :props="{ label: 'label', children: 'children' }"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="deptTreeRef"
              node-key="id"
              highlight-current
              default-expand-all
              @node-click="handleNodeClick"
            />
          </div>
        </el-col>
        <!--用户数据-->
        <el-col :span="16" :xs="24">
          <el-form
            :model="queryParams"
            ref="queryRef"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
          >
            <el-form-item  prop="userName">
              <el-input
                v-model="queryParams.userName"
                placeholder="请输入用户名"
                clearable
                style="width: 160px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item  prop="nickName">
              <el-input
                v-model="queryParams.nickName"
                placeholder="请输入姓名"
                clearable
                style="width: 160px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item  prop="phonenumber">
              <el-input
                v-model="queryParams.phonenumber"
                placeholder="请输入手机号码"
                clearable
                style="width: 160px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <!-- <div>{{ selectName }}</div> -->
          <div class="flex gap-2"  v-if="multiple" style="margin-bottom: 10px;max-height: 60px;overflow-y: auto;">
            <el-tag @close="tagClose(tag)" v-for="tag in arrInfoSelection" :key="tag.name" closable  style="margin-right: 5px; margin-top: 5px;">
              {{ tag.name }}
            </el-tag>
          </div>
          <!-- <el-row :gutter="10" class="mb8">
            <right-toolbar
              v-model:showSearch="showSearch"
              @queryTable="getList"
            ></right-toolbar>
          </el-row> -->

          <el-table
            v-if="open"
            v-loading="loading"
            :data="userList"
            row-key="userName"
            border
            highlight-current-row
            @current-change="handleCurrentChange"
            @select="handleSelectionChange"
            @select-all="selectAll"
            :maxHeight="'calc(65vh - 210px)'"
            ref="userTable"
          >
            <el-table-column
              v-if="multiple"
              type="selection"
              width="50"
              align="center"
            />
            <el-table-column
              label="用户编号"
              align="center"
              key="userId"
              prop="userId"
            />
            <el-table-column
              label="用户名"
              align="center"
              key="userName"
              prop="userName"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="姓名"
              align="center"
              key="nickName"
              prop="nickName"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="组织"
              align="center"
              key="deptName"
              prop="dept.deptName"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="手机号码"
              align="center"
              key="phonenumber"
              prop="phonenumber"
              width="120"
            />
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </el-col>
      </el-row>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="UserSelect">
import { listUser } from "@/api/system/user";
// import {  deptTreeSelect } from "@/api/system/role";
import { treeselect } from "@/api/system/dept";
import { nextTick, toRefs, watch } from "vue";
const { proxy } = getCurrentInstance();

const props = defineProps({
  placeholder: {
    type: String,
    default: "",
  },
  title: {
    type: String,
    default: "",
  },
  multiple: {
    type: Boolean,
    default: true,
  },
  showInput: {
    type: Boolean,
    default: true,
  },
});
const { title, placeholder, multiple, showInput } = toRefs(props);
const emit = defineEmits(["change", "submit","submits"]);
const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const selectionData = ref([]);
const single = ref(true);

const selectObj = ref({});
const userTable = ref();
const total = ref(0);
const selectData = ref([]);
const deptName = ref("");
const deptOptions = ref(undefined);
const currentRow = ref();
const selectName = defineModel();
const selectValue = defineModel("code");
const arrInfoSelection = ref([])
const selectNameList = ref([])
const selectValueList = ref([])


const selectList = ref([])




// 用户状态 仅取正常值
const userStatus = "0";

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    nickName: undefined,
    phonenumber: undefined,
    status: userStatus,
    deptId: undefined,
  },
});

const { queryParams } = toRefs(data);

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

/** 根据名称筛选组织树 */
watch(deptName, (val) => {
  proxy.$refs["deptTreeRef"].filter(val);
});

/** 查询组织下拉树结构 */
function getDeptTree() {
  treeselect().then((response) => {
    deptOptions.value = response.data;
  });
}
const handleCurrentChange = (val) => {
  if (!multiple.value) {
    currentRow.value = val;
  }
};
function tagClose(tag){
  arrInfoSelection.value = arrInfoSelection.value.filter(item=>item.code!=tag.code)
  // 删除之后把表格中的勾选 去掉
  if(userList.value.length){
    userList.value.forEach(item=>{
      const include = arrInfoSelection.value.filter(info=>info.code == item.userId)
      if(include.length){
        userTable.value.toggleRowSelection(item, true);
      } else{
        userTable.value.toggleRowSelection(item, false);
      }
    })
  }

}
function submitForm() {
  if (!multiple.value) {
    selectName.value = currentRow.value.nickName;
    selectValue.value = currentRow.value.userId;
    open.value = false;
    emit("change", { name: selectName.value, id: selectValue.value });
    emit("submit", currentRow.value);
    return;
  }
  const selectArr = [];
  const nameStr = [];
  // for (const key in selectObj.value) {
  //   const el = selectObj.value[key];
  //   if (el.length) {
  //     el.forEach((item) => {
  //       nameStr.push(item.nickName);
  //       selectArr.push(item.userId);
  //     });
  //   }
  // }
  if(arrInfoSelection.value.length){
    arrInfoSelection.value.forEach(item=>{
      nameStr.push(item.name);
      selectArr.push(item.code);
    })
  }
  selectName.value = nameStr.join(",");
  selectValue.value = selectArr.join(",");
  open.value = false;
  emit("change", { name: selectName.value, id: selectValue.value });
  emit("submit", selectionData.value);
  emit("submits", { name: selectName.value, id: selectValue.value });
}
function cancel() {
  open.value = false;
}

function handlePicker() {
  open.value = true;
  selectObj.value = {};
  selectList.value = []
  arrInfoSelection.value = []
  // 组装已选择的数据 多选模式下
  if(selectName.value && selectValue.value && multiple.value){
    selectNameList.value  =  selectName.value.split(',')
    selectValueList.value  =  selectValue.value.split(',')
    selectNameList.value.forEach((item,index)=>{
      arrInfoSelection.value.push({
        name:item,
        code:selectValueList.value[index]
      })
    })
  }
  resetQuery();
  getDeptTree();
  getList();
}

/** 查询用户列表 */
function getList() {
  loading.value = true;
  listUser(queryParams.value).then((res) => {
    loading.value = false;
    userList.value = res.rows;
    total.value = res.total;
    nextTick(() => {
      if(userList.value.length && arrInfoSelection.value.length){
        userList.value.forEach(item=>{
          const include = arrInfoSelection.value.filter(info=>info.code == item.userId)
          if(include.length){
            userTable.value.toggleRowSelection(item, true);
          }
        })
      }
      // if (
      //   selectObj.value[queryParams.value.pageNum] &&
      //   selectObj.value[queryParams.value.pageNum].length > 0
      // ) {
      //   let _arr = selectObj.value[queryParams.value.pageNum].map((item) => {
      //     return item.userId;
      //   });
      //   for (let i in userList.value) {
      //     const item = userList.value[i];
      //     if (_arr.includes(item.userId)) {
      //       userTable.value.toggleRowSelection(item, true);
      //     }
      //   }
      // }
    });
  });
}

/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.deptId = data.id;
  handleQuery();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.deptId = undefined;
  queryParams.value.status = userStatus;
  // proxy.$refs.deptTreeRef.setCurrentKey(null);
  handleQuery();
}
// 数组对象去重
function uniqueObjects(arr) {
  const seen = new Map();
  return arr.filter(item => {
    // 将对象转换为字符串（或其他可以唯一表示对象的内容）
    const key = JSON.stringify(item);
    // 如果 Map 中还没有这个键，则添加它并返回 true
    if (!seen.has(key)) {
      seen.set(key, item);
      return true;
    }
    // 如果已经有了，就返回 false，表示这个对象应该被过滤掉
    return false;
  });
}
// 全选 或全不选
function selectAll(section){
  if(section.length){
    // 全选  push
    section.forEach(item=>{
      arrInfoSelection.value.push({
        name:item.nickName,
        code:item.userId+''
      })
    })
  } else {
    // 全不选  当页数据  删除
    if(userList.value.length && arrInfoSelection.value.length){
        userList.value.forEach(item=>{
          arrInfoSelection.value = arrInfoSelection.value.filter(info=>item.userId!=info.code)
          // userTable.value.toggleRowSelection(item, true);
        })
      }
  }
  arrInfoSelection.value = uniqueObjects(arrInfoSelection.value)
}
/** 选择条数  */
function handleSelectionChange(selection,row) {
  let selected = selection.length && selection.indexOf(row) !== -1
	console.log(selected)  // 判断操作时  true就是选中，0或者false是取消选中
  if(selected){
    arrInfoSelection.value.push({
      name:row.nickName,
      code:row.userId+''
    })
  } else {
    arrInfoSelection.value = arrInfoSelection.value.filter(item=>item.code!=row.userId)
  }

  ids.value = selection.map((item) => item.userId);
  single.value = selection.length != 1;
  // selectData.value = selection.map((item) => item.nickName);
  // selectionData.value = selection;
  selectObj.value[queryParams.value.pageNum] = selection;
}
defineExpose({
  handlePicker,
});
</script>
